package com.weiyuwqj.server.service.asset.impl;

import com.github.pagehelper.PageHelper;
import com.weiyuwqj.api.common.Calculator;
import com.weiyuwqj.api.common.PageList;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.common.RepayPlan;
import com.weiyuwqj.api.constant.OperateContants;
import com.weiyuwqj.api.exception.CrowdException;
//import com.weiyuwqj.api.hengfeng.model.base.HfBaseResponseBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.model.item.HfCommission;
//import com.weiyuwqj.api.hengfeng.model.item.HfItemTransferDebt;
//import com.weiyuwqj.api.hengfeng.model.platform.HfFundFreezeOrTraw;
import com.weiyuwqj.api.model.BasAssetsPackage;
import com.weiyuwqj.api.model.BasItem;
import com.weiyuwqj.api.model.BasUser;
import com.weiyuwqj.api.model.BusAssetCollect;
import com.weiyuwqj.api.model.BusAssetInvest;
import com.weiyuwqj.api.model.BusAssetPackagePlan;
import com.weiyuwqj.api.model.BusAssetRepay;
import com.weiyuwqj.api.model.vo.BusAssetPackageInvestVo;
import com.weiyuwqj.api.model.vo.BusAssetPackagePlanVO;
import com.weiyuwqj.api.service.BusAssetPackagePlanService;
import com.weiyuwqj.api.service.ContractsGeneratorService;
import com.weiyuwqj.api.util.DateUtils;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.JsonUtils;
import com.weiyuwqj.api.util.RandomCodesUtils;
import com.weiyuwqj.api.util.StringUtils;
import com.weiyuwqj.server.auto.BusItemAutoInvest;
import com.weiyuwqj.server.mapper.BasAssetsPackageMapper;
import com.weiyuwqj.server.mapper.BasItemMapper;
import com.weiyuwqj.server.mapper.BasUserMapper;
import com.weiyuwqj.server.mapper.BusAssetCollectMapper;
import com.weiyuwqj.server.mapper.BusAssetInvestMapper;
import com.weiyuwqj.server.mapper.BusAssetPackageInvestMapper;
import com.weiyuwqj.server.mapper.BusAssetPackagePlanMapper;
import com.weiyuwqj.server.mapper.BusAssetRepayMapper;
import com.weiyuwqj.server.mapper.BusIncomeStatMapper;
//import com.weiyuwqj.server.pay.InvestApi;
//import com.weiyuwqj.server.pay.PlatformApi;
import com.weiyuwqj.server.service.account.module.DealAction;
import com.weiyuwqj.server.service.account.module.DealModule;
import com.weiyuwqj.server.service.account.module.action.debt.DebtInvestFreezeDealAction;
import com.weiyuwqj.server.service.account.module.action.debt.DebtInvestWaitDealAction;
import com.weiyuwqj.server.service.account.module.action.debt.DebtLoanUsableDealAction;
import com.weiyuwqj.server.service.account.module.action.debt.DebtLoanWaitDealAction;
import com.weiyuwqj.server.service.account.module.action.user.invest.GenerateWaitDealAction;
import com.weiyuwqj.server.service.account.module.action.user.invest.InvestDeductDealAction;
import com.weiyuwqj.server.service.base.BaseServiceImpl;
import com.weiyuwqj.server.service.finance.module.OperateModule;
import com.weiyuwqj.server.service.finance.module.action.ExpendOperateAction;
import com.weiyuwqj.server.service.finance.module.action.OperateAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/29.
 */
@Service("busAssetPackagePlanService")
public class BusAssetPackagePlanServiceImpl extends BaseServiceImpl<BusAssetPackagePlan> implements BusAssetPackagePlanService {

    @Autowired
    private BusAssetPackagePlanMapper busAssetPackagePlanMapper;
    @Autowired
    private BusAssetInvestMapper assetInvestMapper;
    @Autowired
    private BusAssetPackageInvestMapper assetPackageInvestMapper;
    @Autowired
    private BasAssetsPackageMapper assetsPackageMapper;
    @Autowired
    private BasItemMapper itemMapper;
    @Autowired
    private BusAssetCollectMapper assetCollectMapper;
    @Autowired
    private BusAssetRepayMapper assetRepayMapper;
    @Autowired
    private DealModule dealModule;
    @Autowired
    private BusIncomeStatMapper incomeStatMapper;
    @Autowired
    private BasUserMapper userMapper;
    @Autowired
    private BusItemAutoInvest autoInvest;
    @Autowired
    private ContractsGeneratorService contractsGeneratorService;
    @Autowired
    private OperateModule operateModule;
//	@Autowired
//	private InvestApi investApi;
//
//
//    @Autowired
//    private PlatformApi platformApi;


    /**
     * 资产包计划列表
     * @param busAssetPackagePlan
     * @return
     */
    @Override
    public PageList getPackagePlanList(Paginator p, BusAssetPackagePlan busAssetPackagePlan) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<BusAssetPackagePlan> list = busAssetPackagePlanMapper.getPackagePlanList(busAssetPackagePlan);
        return new PageList(list);
    }

    @Override
    public Map listInvestBeforeMatch(Integer packagePlanId) {
        BusAssetPackagePlan plan = busAssetPackagePlanMapper.selectByPrimaryKey(packagePlanId);
        Integer lastPeriod = plan.getPeriods() - 1;
        List<BusAssetPackageInvestVo> packageInvestList=assetPackageInvestMapper.getListByPlanId(packagePlanId);
        List<BusAssetInvest> assetInvestList = assetInvestMapper.listByPackageIdAndPeriod(plan.getAssetPackageId(),lastPeriod);
        //查询包信息
        BasAssetsPackage assetsPackage = assetsPackageMapper.selectByPrimaryKey(plan.getAssetPackageId());
        for(BusAssetPackageInvestVo assetPackageInvestVo:packageInvestList){
            BigDecimal num = assetPackageInvestVo.getInvestDealAmount().divide(assetsPackage.getEachAmount(),0,BigDecimal.ROUND_HALF_UP);
            assetPackageInvestVo.setInvestDealAmount(num);
        }
        for(BusAssetInvest assetInvest:assetInvestList){
            BigDecimal num = assetInvest.getInvestDealAmount().divide(assetsPackage.getEachAmount(), 0, BigDecimal.ROUND_HALF_UP);
            assetInvest.setInvestDealAmount(num);
        }
        Map map = new HashMap();
        map.put("packageInvestList",packageInvestList);
        map.put("assetInvestList",assetInvestList);
        return map;
    }

//    /**
//     * 匹配
//     * @param matchJson json串
//     * @param packagePlanId 资产计划id
//     */
//    @Override
//    public void investMatch(String matchJson,Integer packagePlanId) {
//
//        List<BusAssetPackageInvestVo> list = assetPackageInvestMapper.getListByPlanId(packagePlanId);
//
//        Boolean thaw = true;
//        for(BusAssetPackageInvestVo itemInvest:list){
//            HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//            freezeOrTraw.setAmount(itemInvest.getInvestDealAmount().toString());
//            freezeOrTraw.setFreeze_flg("02");
//            freezeOrTraw.setPlatcust(userMapper.selectByPrimaryKey(itemInvest.getUserId()).getPlatformId());
//            freezeOrTraw.setRemark(itemInvest.getUserId()+"投资撤回");
//            freezeOrTraw.setOrder_no(StringUtils.getOrderNo());
//            freezeOrTraw.setFreeze_order_no(itemInvest.getFreezeOrderNo());
//            HfResultBean result = null; // 请求恒丰
//            try {
//                result = platformApi.doFundFreeze(freezeOrTraw);
//            } catch (Exception e) {
//                thaw = false;
//            }
//        }
//        //判断是否完成解冻
//        if(!thaw){
//            throw new CrowdException("item.recall.thaw_error");
//        }
//        //根据计划id查询计划表记录
//        BusAssetPackagePlan assetPackagePlan = busAssetPackagePlanMapper.selectByPrimaryKey(packagePlanId);
//        //修改上一期的投资记录债转状态
//        List<BusAssetInvest> assetInvestList =assetInvestMapper.getAssetInvestListByPackagePlanIdAndPeriods(assetPackagePlan.getPeriods()-1,assetPackagePlan.getAssetPackageId());
//        for(BusAssetInvest assetInvest:assetInvestList){
//            assetInvestMapper.modifyAssetInvestDebtTransferStatusById(1,0,assetInvest.getId());
//        }
//
//        //根据包id找包记录
//        BasAssetsPackage assetsPackage = assetsPackageMapper.selectByPrimaryKey(assetPackagePlan.getAssetPackageId());
//        //每份金额
//        BigDecimal eachAmount = assetsPackage.getEachAmount();
//        //解析json
//        List matchList = JsonUtils.json2Object(matchJson, ArrayList.class);
//        for(int i=0;i<matchList.size();i++){
//            //债转前，债转后
//            Map matchMap = (Map)matchList.get(i);
//            //债转前列表[{id:**,userId:***,partNumber:**},{}]
//            List beforeList = (List)matchMap.get("beforeList");
//            //债转后列表[{id:**,userId:***,partNumber:**},{}]
//            List laterList = (List)matchMap.get("laterList");
//            //判断两列表的长度，拆长度小的列表
//            if(beforeList.size()>laterList.size()){
//                //循环前列表
//                for(int j=0;j<beforeList.size();j++){
//                    Map beforeMap = (Map)beforeList.get(i);
//                    for(int k=0;k<laterList.size();k++){
//                        Map laterMap = (Map)laterList.get(k);
//                        //插入资产投资表
//                        insertAssetInvest(assetPackagePlan, eachAmount, beforeMap, laterMap, packagePlanId);
//                    }
//                }
//            }else{
//                //循环后列表
//                for(int j=0;j<laterList.size();j++){
//                    Map laterMap = (Map)laterList.get(j);
//                    for(int k=0;k<beforeList.size();k++){
//                        Map beforeMap = (Map)beforeList.get(k);
//                        insertAssetInvest(assetPackagePlan, eachAmount, beforeMap, laterMap, packagePlanId);
//                    }
//                }
//            }
//        }
//        //根据包id查询表列表
//        List<BasItem> itemList = itemMapper.getItemListByPackageId(assetPackagePlan.getAssetPackageId());
//        //还款时间
//        Date repayTime = new Date();
//        //循环标列表，标成立（复审成功）
//        for(BasItem item:itemList){
//            repayTime= fullVerifySuccess(item.getId(),repayTime,assetPackagePlan.getPeriods());
//        }
//        //更新包计划表
//        busAssetPackagePlanMapper.modifyRepayTimeById(repayTime,packagePlanId);
//        busAssetPackagePlanMapper.modifyStatusById(4, packagePlanId);
//    }


//    /**
//     * 插入资产投资记录表
//     * @param assetPackagePlan
//     * @param eachAmount
//     * @param beforeMap
//     * @param laterMap
//     * @param packagePlanId
//     */
//    public void insertAssetInvest(BusAssetPackagePlan assetPackagePlan, BigDecimal eachAmount, Map beforeMap,
//                                  Map laterMap, Integer packagePlanId) {
//        //插入资产投资表
//        BusAssetInvest assetInvest = new BusAssetInvest();
//        assetInvest.setAddip(IpUtils.get());
//        assetInvest.setAddtime(new Date());
//        assetInvest.setInvestOrder(RandomCodesUtils.getOrderNo());
//        assetInvest.setInvestStatus(0);
//        assetInvest.setInvestType(7);
//        assetInvest.setUserId(Integer.valueOf(laterMap.get("userId").toString()));
//        assetInvest.setUpdatetime(new Date());
//        assetInvest.setDebtTransferStatus(0);
//        if(Integer.valueOf(beforeMap.get("id").toString())<1||Integer.valueOf(beforeMap.get("id").toString())==null){
//            assetInvest.setParentId(0);
//        }else {
//            assetInvest.setParentId(Integer.valueOf(beforeMap.get("id").toString()));
//        }
//        assetInvest.setPackagePlanId(packagePlanId);
//        assetInvest.setInvestAmount(new BigDecimal(laterMap.get("investDealAmount").toString()).multiply(eachAmount));//投资金额
//        assetInvest.setInvestDealAmount(assetInvest.getInvestAmount());//实际成交金额
//        assetInvest.setItemId(Integer.valueOf(beforeMap.get("itemId").toString()));
//        //待赚收益
//        BigDecimal earnAmount = assetInvest.getInvestAmount().multiply(assetPackagePlan.getRate()).
//                divide(new BigDecimal(1200), 2, BigDecimal.ROUND_DOWN);
//        assetInvest.setCollectAmount(assetInvest.getInvestAmount().add(earnAmount));//应收总额
//        assetInvest.setCollectPrincipal(assetInvest.getInvestAmount());//应收本金
//        assetInvest.setCollectInterest(earnAmount);//应收利息
//        assetInvest.setActualCollectAmount(BigDecimal.ZERO);
//        assetInvest.setActualCollectInterest(BigDecimal.ZERO);
//        assetInvest.setActualCollectPrincipal(BigDecimal.ZERO);
//        assetInvest.setActualUncollectAmount(BigDecimal.ZERO);
//        assetInvest.setActualUncollectInterest(BigDecimal.ZERO);
//        assetInvest.setActualUncollectPrincipal(BigDecimal.ZERO);
//        assetInvest.setAdditionalRateAmount(BigDecimal.ZERO);
//        //int investId = assetInvestMapper.insert(assetInvest); // 主键
//        assetInvestMapper.saveBean(assetInvest);
//
//        //查询转让人信息
//        BasUser transferorUser =  userMapper.selectByPrimaryKey(Integer.parseInt(beforeMap.get("userId").toString()));
//        //查询受让人信息
//        BasUser transfereeUser =  userMapper.selectByPrimaryKey(Integer.parseInt(laterMap.get("userId").toString()));
//        //标信息
//
//        BasItem item = itemMapper.selectByPrimaryKey(Integer.valueOf(beforeMap.get("itemId").toString()));
//
//        BigDecimal amount= new BigDecimal(laterMap.get("investDealAmount").toString());
//        //请求恒丰标转让接口
//        HfItemTransferDebt itemTransferDebt=new HfItemTransferDebt();
//        itemTransferDebt.setOrder_no(assetInvest.getInvestOrder());               //订单号
//        itemTransferDebt.setPlatcust(transferorUser.getPlatformId());             //转让人平台号
//        itemTransferDebt.setTrans_share(amount.toString());   //转让份额
//        itemTransferDebt.setProd_id(item.getId().toString());                        //产品编号
//        itemTransferDebt.setDeal_amount(amount.multiply(eachAmount).toString());                                     //自费价格
//        itemTransferDebt.setCoupon_amt("0");                                      //抵用劵金额
//        itemTransferDebt.setDeal_platcust(transfereeUser.getPlatformId());        //受让人平台号
//        itemTransferDebt.setPublish_date(DateUtils.getDateTime());                //发布时间
//        itemTransferDebt.setTrans_date(DateUtils.getDateTime());                  //成交时间
//        itemTransferDebt.setTransfer_income("0");                                 //转让收益
//        itemTransferDebt.setIncome_acct("01");                                    //收益出资方账户 平台：01  ；个人：对应platcust
//	    //itemTransferDebt.setSubject_priority("0");                                //科目优先级0-可提优先1可投优先
//	    itemTransferDebt.setPartner_trans_time(DateUtils.getTimeForHengfeng());
//        itemTransferDebt.setTrans_amt(amount.multiply(eachAmount).toString());
//        itemTransferDebt.setPartner_trans_date(DateUtils.getDateForHengfeng());
//        itemTransferDebt.setRelated_prod_ids(item.getId().toString());
//        HfCommission commission = new HfCommission();
//        commission.setPayout_amt("0.00");
//        commission.setPayout_plat_type("01");
//        itemTransferDebt.setCommission(commission);
//	    HfResultBean resultBean = investApi.transferDebt(itemTransferDebt); // 请求恒丰
//	    //成功
//	    if (resultBean.isSuccess()) {
//		    //处理账户资金
//            //扣除投资债权人冻结资金
//            DealAction debtFreeze=new DebtInvestFreezeDealAction();
//            debtFreeze.deal(Integer.parseInt(laterMap.get("userId").toString()),assetInvest.getInvestDealAmount(),"扣除投资债权人冻结金额");
//            dealModule.dealAction(debtFreeze);
//            //产生待收
//            DealAction debtWait=new DebtInvestWaitDealAction();
//            debtWait.deal(Integer.parseInt(laterMap.get("userId").toString()),assetInvest.getCollectAmount(),"产生投资债权人待收金额");
//            dealModule.dealAction(debtWait);
//            //减去债权人待收，增加可用可提
//            DealAction debtLoanWait=new DebtLoanWaitDealAction();
//            debtLoanWait.deal(Integer.parseInt(beforeMap.get("userId").toString()),assetInvest.getCollectAmount(),"扣除债权人待收金额");
//            dealModule.dealAction(debtLoanWait);
//            DealAction debtLoanUsable=new DebtLoanUsableDealAction();
//            debtLoanUsable.deal(Integer.parseInt(beforeMap.get("userId").toString()),assetInvest.getInvestDealAmount(),"产生债权人可用，可提");
//            dealModule.dealAction(debtLoanUsable);
//
//            //修改资产计划状态
//            assetPackageInvestMapper.modifyPackageInvestStatusById(1,2,Integer.parseInt(laterMap.get("id").toString()));
//
//		    // todo 包计划 合同生成
//		    contractsGeneratorService.generateContractsByPackage(assetInvest.getUserId(), assetInvest.getId(), assetInvest.getInvestOrder(), packagePlanId);
//	    }else {
//            //失败，修改资产计划状态
//            assetPackageInvestMapper.modifyPackageInvestStatusById(0,2,Integer.parseInt(laterMap.get("id").toString()));
//        }
//    }

    /**
     * 打包的标复审
     * @param itemId
     */
    public Date fullVerifySuccess(int itemId, Date repayTime,Integer periods) {
        //根据标id查询标信息
        BasItem item = itemMapper.selectByPrimaryKey(itemId);
        //投资人动作
        List<BusAssetInvest> assetInvestList = assetInvestMapper.getNotDebtAssetInvestListByItemId(itemId);
        //本金
        BigDecimal itemPrincial = BigDecimal.ZERO;
        //利息
        BigDecimal itemInterest = BigDecimal.ZERO;
        //统计每个投资的人的分期数据
        List<BigDecimal[]> princialList = new ArrayList<>(assetInvestList.size());
        List<BigDecimal[]> interestList = new ArrayList<>(assetInvestList.size());
        Date repayDate = new Date();
        Integer totalPeriod = 0;
        Integer currentPeriod = 0;

        //循环投资人列表
        for (int i = 0; i < assetInvestList.size(); i++) {
            BusAssetInvest assetInvest = assetInvestList.get(i);
            //根据项目利率计算利息
            List<RepayPlan> repayPlanList = Calculator.getPlanTime(assetInvest.getInvestDealAmount(), item);//项目利率的

            List<RepayPlan> copyRepayPlanList = new ArrayList<>();

            copyRepayPlanList.addAll(repayPlanList);

            for(int k =0;k<periods-1;k++){
                repayPlanList.remove(0);
            }
            //投资本金
            BigDecimal investPrincial = BigDecimal.ZERO;
            //投资利息
            BigDecimal investInterest = BigDecimal.ZERO;
            //本金待收数组
            BigDecimal[] princialCollectArray = new BigDecimal[repayPlanList.size()];
            //利息待收数组
            BigDecimal[] interestCollectArray = new BigDecimal[repayPlanList.size()];
            for (int j = 0; j < 1; j++) {
                RepayPlan plan = repayPlanList.get(j);
                //插入资产待收表
                BusAssetCollect collect = new BusAssetCollect();
                collect.setItemId(itemId);
                BusAssetPackagePlan assetPackagePlan = busAssetPackagePlanMapper.selectByPrimaryKey(assetInvest.getPackagePlanId());
                collect.setPackageId(assetPackagePlan.getAssetPackageId());
                collect.setCollectAmount(plan.getAccount());
                collect.setCollectTotalPeriod(copyRepayPlanList.size());
                collect.setCollectCurrentPeriod(plan.getPeriod());
                collect.setCollectPrincipal(plan.getPrincipal());
                collect.setCollectInterest(plan.getInterest());
                collect.setCollectTime(plan.getEndTime());
                collect.setActualCollectAmount(BigDecimal.ZERO);
                collect.setActualCollectPrincipal(BigDecimal.ZERO);
                collect.setActualCollectInterest(BigDecimal.ZERO);
                collect.setAddip(IpUtils.get());
                collect.setAddtime(new Date());
                collect.setInvestId(assetInvest.getId());
                collect.setInvestUserId(assetInvest.getUserId());
                collect.setCollectStatus(0);
                collect.setDebtTransferStatus(0);
                collect.setAdditionalRateAmount(BigDecimal.ZERO);
                //查询用户信息
                BasUser user = userMapper.selectByPrimaryKey(assetInvest.getUserId());
                collect.setPlatformId(user.getPlatformId());
                assetCollectMapper.insert(collect);

                princialCollectArray[j] = plan.getPrincipal();
                interestCollectArray[j] = plan.getInterest();
                investInterest = investInterest.add(plan.getInterest());
                investPrincial = investPrincial.add(plan.getPrincipal());

                repayDate = plan.getEndTime();
                totalPeriod=collect.getCollectTotalPeriod();
                currentPeriod=collect.getCollectCurrentPeriod();
            }
            princialList.add(princialCollectArray);
            interestList.add(interestCollectArray);
            //投标时已经计算预计回收金额、利息，现在清0重新计算，以复审后为准
            assetInvest.setCollectAmount(BigDecimal.ZERO);
            assetInvest.setCollectInterest(BigDecimal.ZERO);
            assetInvest.setCollectPrincipal(BigDecimal.ZERO);
            //修改状态，并修改投资金额
            assetInvestMapper.updateAssetInvestStatus(0, 1, assetInvest.getId());
            assetInvestMapper.updateAssetFullInvestCollect(investPrincial, investInterest, assetInvest.getId());

            itemPrincial = itemPrincial.add(investPrincial);
            itemInterest = itemInterest.add(investInterest);
            //扣除用户冻结金额
//            DealAction deduct = new InvestDeductDealAction();
//            deduct.deal(assetInvest.getUserId(), assetInvest.getInvestDealAmount(), "扣除" + item.getItemName() + "项目投资冻结资金");
//            dealModule.dealAction(deduct);
//            OperateAction operate = new ExpendOperateAction();
//            operate.operateAction(assetInvest.getInvestOrder(), OperateContants.INVESTORS_INVEST,itemId,
//                    item.getItemName(),assetInvest.getInvestDealAmount());
//            operateModule.operateAction(operate);
//            //产生用户待收金额
//            DealAction wait = new GenerateWaitDealAction();
//            wait.deal(assetInvest.getUserId(), assetInvest.getInvestDealAmount().add(investInterest), item.getItemName() + "产生待收资金");
//            dealModule.dealAction(wait);

            //复审通过使income_stat表修改待收
            BusAssetInvest busItemInvest = assetInvestList.get(i);
            Map<String, Object> map = new HashMap<>();
            map.put("waitIncome", investInterest);
            map.put("userId", busItemInvest.getUserId());
            map.put("earnedIncome", 0);
            map.put("totalIncome", investInterest);
            incomeStatMapper.updateByWaitEarned(map);
        }
        //借款人动作
        if (princialList.size() > 0) {
            int planLength = princialList.get(0).length;
            for (int j = 0; j < 1; j++) {
                BigDecimal princial = BigDecimal.ZERO;
                BigDecimal interest = BigDecimal.ZERO;
                BigDecimal additional = BigDecimal.ZERO;
                for (int i = 0; i < princialList.size(); i++) {
                    BigDecimal[] pa = princialList.get(i);
                    BigDecimal[] ia = interestList.get(i);
                    princial = princial.add(pa[j]);
                    interest = interest.add(ia[j]);
                }
                BusAssetRepay repay = new BusAssetRepay();
                BigDecimal amount = princial.add(interest);
                repay.setPackageId(item.getAssetPackageId());
                repay.setRepayUserId(item.getItemUserId());
                repay.setRepayAmount(amount);
                repay.setRepayPrincipal(princial);
                repay.setAdditionalRateAmount(additional);
                repay.setRepayInterest(interest);
                repay.setItemId(itemId);
                repay.setRepayCurrentPeriod(currentPeriod);
                repay.setRepayTotalPeriod(totalPeriod);
                repay.setStatus(0);
                repay.setActualRepayAmount(BigDecimal.ZERO);
                repay.setActualRepayInterest(BigDecimal.ZERO);
                repay.setActualRepayPrincipal(BigDecimal.ZERO);
                repay.setRepayTime(repayDate);
                assetRepayMapper.insert(repay);
                repayTime = repay.getRepayTime();
            }
        }
        return repayTime;
    }

    @Override
    public List<BusAssetPackagePlan> getPlanList() {
        return busAssetPackagePlanMapper.getPlanList();
    }

    /**
     * 根据id修改还款时间
     * @param beforeRepayTime
     * @param id
     * @return
     */
    @Override
    public Integer modifyRepayTimeById(Date beforeRepayTime, Integer id) {
        return busAssetPackagePlanMapper.modifyRepayTimeById(beforeRepayTime, id);
    }

//    /**
//     * 根据id修改包状态
//     * @param status 1-等待发布，2-投资中，3-已满标，4-已匹配审核
//     * @param id
//     * @param sign   标志，1标明复审调用，2标明触发自动投标
//     * @return
//     */
//    @Override
//    public void modifyStatusById(Integer status, Integer id,int sign) {
//        //判断上一期是否复审
//        BusAssetPackagePlanVO assetPackagePlanVO = busAssetPackagePlanMapper.getAssetPackagePlanById(id);
//        BusAssetPackagePlan assetPackagePlan = busAssetPackagePlanMapper.getPlanByPackageIdAndPeriods(assetPackagePlanVO.getAssetPackageId(), assetPackagePlanVO.getPeriods() - 1);
//        if(assetPackagePlan!=null){
//            if(assetPackagePlan.getStatus()!=4){
//                throw new CrowdException("packagePlan.last_term.not_full");
//            }
//        }
//
//        busAssetPackagePlanMapper.modifyStatusById(status, id);
//        busAssetPackagePlanMapper.modifyPackagePlanByReleaseTime(new Date(),id);
//        if(sign==2){
//            autoInvest.basAssetsPackageMatchingAutoRule(busAssetPackagePlanMapper.selectByPrimaryKey(id));
//        }
//    }

    /**
     * 查询可投资的包计划
     * @return
     */
    @Override
    public PageList getAssetPlanList(Paginator p) {
        PageHelper.startPage(p.getPageNum(),p.getPageSize());
        List<BusAssetPackagePlan> list = busAssetPackagePlanMapper.getAssetPlanList();
        return new PageList(list);
    }

    /**
     * 根据id查询单个信息
     * @param id
     * @return
     */
    @Override
    public BusAssetPackagePlanVO getAssetPackagePlanById(Integer id) {
        BusAssetPackagePlanVO assetPackagePlanVO = busAssetPackagePlanMapper.getAssetPackagePlanById(id);
        //查询包信息
        BasAssetsPackage assetsPackage = assetsPackageMapper.selectByPrimaryKey(assetPackagePlanVO.getAssetPackageId());
        BigDecimal num = assetPackagePlanVO.getAmount().subtract(assetPackagePlanVO.getOngoingAccount()).divide(assetsPackage.getEachAmount(), 2, RoundingMode.HALF_DOWN);
        assetPackagePlanVO.setNumber(num.intValue());
        assetPackagePlanVO.setEachAmount(assetPackagePlanVO.getEachAmount());
        return assetPackagePlanVO;
    }

}
